﻿using Hjt212Parser;
using HpSocketIotGateway.Db.Code1st;
using HpSocketIotGateway.Properties;
using log4net;
using System;
using System.Linq;
using ToolsAndHjt212Parser;

namespace HpSocketIotGateway.Facade
{
    public class BizPersistence
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(BizPersistence));
        public static void Persist(string content)
        {
            try
            {
                using (var ctx = new GatewayContext())
                {
                    var mn = Parser.GetStringByKey("MN", content);
                    if (!MyValidation.IsMnValid(mn))
                    {
                        return;
                    }

                    if (Parser.IsHeartBeatPackage(content))
                    {
                        BizStatus.SetOnline(mn);
                        return;
                    }
                    var dateTimeByKey = Parser.GetDateTimeByKey("DataTime", content);
                    var cn = Parser.GetStringByKey("CN", content);
                    if (string.IsNullOrEmpty(cn))
                    {
                        cn = Parser.GetStringByKey("ST", content);
                    }

                    var qn = Parser.GetStringByKey("QN", content);
                    if (!string.IsNullOrEmpty(mn))
                    {
                        var isRight = Parser.IsLengthRight(content) && Parser.IsCrcRight(content);
                        var isDatatimeReasonable = DateTimeHelper.IsRecentlyYear(dateTimeByKey);
                        isRight = isRight && isDatatimeReasonable;

                        if (cn.Equals("9014"))
                        {
                            var dataItems = ctx.send_data.Where(t => t.qn != null && t.qn.Equals(qn)).ToList();
                            foreach (var dataItem in dataItems)
                            {
                                dataItem.rtn_9014 = "Resp";
                            }
                            ctx.SaveChanges();
                            return;
                        }

                        //var isExist =
                        //    ctx.received_msg
                        //        .Where(t => t.mn.Equals(mn) && t.cn.Equals(cn) && t.datatime == (dateTimeByKey))
                        //        .Where(t => t.received_string != null && t.received_string.Contains(content))
                        //        .FirstOrDefault() != null;
                        var receivedData = new received_msg
                        {
                            received_datetime = DateTime.Now,
                            received_string = content,
                            is_length_right = isRight,
                            datatime = dateTimeByKey,
                            cn = cn,
                            mn = mn,
                            qn = qn,
                            processed_flag = ProcessFlag.NotProcessed.ToString(),//isExist ? ProcessFlag.ProcessingFinished.ToString() : ProcessFlag.NotProcessed.ToString(),
                            processed_flag_2 = ProcessFlag.ProcessingFinished.ToString(),
                            processed_flag_3 = ProcessFlag.ProcessingFinished.ToString()
                        };
                        if (Settings.Default.ProcessorNum == 2)
                        {
                            receivedData.processed_flag_2 = ProcessFlag.NotProcessed.ToString();
                        }
                        else if (Settings.Default.ProcessorNum == 3)
                        {
                            receivedData.processed_flag_2 = ProcessFlag.NotProcessed.ToString();
                            receivedData.processed_flag_3 = ProcessFlag.NotProcessed.ToString();
                        }
                        if ("9021;3099;2081;2072".Contains(receivedData.cn) && MyTimer.IsToTheTime(receivedData.mn + receivedData.cn, 5))
                        //if (!("9014;9012;9011;2031;2061;3071".Contains(receivedData.cn)) && MyTimer.IsToTheTime(receivedData.mn + receivedData.cn, 5))
                        {
                            receivedData.processed_flag = ProcessFlag.ProcessingFinished.ToString();
                            receivedData.processed_flag_2 = ProcessFlag.ProcessingFinished.ToString();
                            receivedData.processed_flag_3 = ProcessFlag.ProcessingFinished.ToString();
                        }
                        var flag = Parser.GetIntByKey("Flag", content);
                        if (SplitPackage.IsSplitPackage(flag))
                        {
                            receivedData.processed_flag = ProcessFlag.ProcessingFinished.ToString();
                            receivedData.processed_flag_2 = ProcessFlag.ProcessingFinished.ToString();
                            receivedData.processed_flag_3 = ProcessFlag.ProcessingFinished.ToString();
                        }
                        ctx.received_msg.Add(receivedData);
                        ctx.SaveChanges();

                        if (SplitPackage.IsSplitPackage(flag))
                        {
                            SplitPackage.SplitPackageProcess(content);
                        }


                        if (Log.IsDebugEnabled)
                        {
                            var factors = Parser.GetPollutantCodes(content);
                            foreach (var factor in factors)
                            {
                                Log.Debug(factor);
                            }
                            var factorExprs = Parser.GetPollutantExprs(content);
                            foreach (var factorExpr in factorExprs)
                            {
                                Log.Debug(factorExpr + ":" + Parser.GetStringByKey(factorExpr, content));
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        public static void PersistGatewayResponseMsg(string content)
        {
            try
            {
                using (var ctx = new GatewayContext())
                {
                    var mn = Parser.GetStringByKey("MN", content);
                    if (string.IsNullOrWhiteSpace(mn))
                    {
                        return;
                    }
                    var cn = Parser.GetStringByKey("CN", content);
                    var qn = Parser.GetStringByKey("QN", content);
                    var sendctrcmd = new send_ctr_cmd()
                    {
                        send_time = DateTime.Now,
                        sent_time = DateTime.Now,
                        send_string = content,
                        is_sent = true,
                        cn = cn,
                        mn = mn,
                        qn = qn,
                        rtn_9011 = "Gate",
                        rtn_9012 = "Gate",
                        rtn_9014 = "Gate"
                    };
                    ctx.send_ctr_cmd.Add(sendctrcmd);
                    ctx.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
    }
}

